import re


def macth_action_item(response, action_space, objects):
    # 使用正则匹配<DecisionMaking>(.*?)</DecisionMaking>中间的内容
    match = re.search(r'<DecisionMaking>(.*?)</DecisionMaking>', response)
    if match:
        # 初步匹配成功
        raw_action = match.group(1)
    else:
        # 初步匹配失败
        return "response", "error", None

    # 遍历action_space找到合法动作前缀
    action = "error"
    raw_action_lower = raw_action.lower()
    for action_name in action_space:
        if raw_action_lower.startswith(action_name.lower()):
            action = action_name
            break

    # 判断action是否需要操作对象
    no_objects_actions = ["end", "observe", "move forward", "error"]
    if any(raw_action_lower.startswith(action) for action in no_objects_actions):
        return raw_action, action, None

    # 动作需绑定一个操作对象item
    raw_item = raw_action.split(" ")[-1].strip()
    for i, obj in enumerate(objects):
        if raw_item.lower() == obj.lower():
            return raw_action, action, obj

    print("需要模糊匹配")
    return raw_action, action, "unknown"

def check_invalid_action(action, action_space):
    for action_name in action_space:
        if action_name.lower() == action.lower():
            return False
    return True
